import {Component, OnInit} from '@angular/core';
import {COMMON_DETAIL, TableDetailModel} from '../../../common/table-detail/table-detail.model';
import {HomeService} from '../../home.service';
import {ArrayConfig, FormInfoModel} from '../../../common/form-info/form-info.model';
import {XcUploadTool} from '../../../common/xc-upload.tool';
import {CommonTool} from '../../../common/common.tool';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import {AppService} from '../../../app.service';
import {BUTTON_CODE} from '../../../config/button-code';
import {PersonalInfoService} from '../personal-info.service';
import {BasicService} from '../../../basic/basic.service';

@Component({
  selector: 'app-personal-info-details',
  templateUrl: './personal-info-details.component.html',
  styleUrls: ['./personal-info-details.component.scss']
})
export class PersonalInfoDetailsComponent implements OnInit {

  public tableDetailModel: TableDetailModel;
  public formInfoModel: FormInfoModel;
  public isVisible = false;
  public userId;
  public editBasicUser = {
    isVisible: false,
    name: ''
  };
  public captchaInfo = {
    account: '',
    captcha: '',
    type: 'email',
    buttonName: '获取验证码'
  };
  public logOffBasic = {
    isVisible: false,
    name: ''
  };
  public isCaptcha = true;
  public captchaInterval;
  public countryOptions = [];
  public provinceOptions = [];
  public cityOptions = [];
  public defaultPortrait = './assets/images/user.png';

  constructor(public homeService: HomeService,
              public message: NzMessageService,
              public appService: AppService,
              public basicService: BasicService,
              public modalService: NzModalService,
              public personalInfoService: PersonalInfoService) {
    this.tableDetailModel = new TableDetailModel();
    this.formInfoModel = new FormInfoModel();
    const that = this;
    this.tableDetailModel.setConfig({
      revertName: '返回',
      revertUrl: '/home',
      modules: [
        {name: '基础信息', type: COMMON_DETAIL.header},
        {
          name: '账号', field: 'account', type: COMMON_DETAIL.block,
          operate: {
            name: '注销',
            style: {marginLeft: '5px'},
            bAuthority: BUTTON_CODE.b_delete_user,
            confirmFun(formInfo) {
              if (that.captchaInterval) {
                clearInterval(that.captchaInterval);
              }
              that.modalService.confirm({
                nzTitle: '确认要注销吗?',
                nzContent: '<b style="color: red;">注销以后将删除你在本平台的所有数据哦！</b>',
                nzOkText: '确认',
                nzOkType: 'danger',
                nzOnOk: () => {
                  that.isCaptcha = true;
                  if (formInfo.phone) {
                    that.logOffBasic = {
                      isVisible: true,
                      name: '手机验证码'
                    };
                    that.captchaInfo = {
                      captcha: '',
                      account: '',
                      type: 'phone',
                      buttonName: '获取验证码'
                    };
                  } else if (formInfo.email) {
                    that.logOffBasic = {
                      isVisible: true,
                      name: '邮箱验证码'
                    };
                    that.captchaInfo = {
                      captcha: '',
                      account: '',
                      type: 'email',
                      buttonName: '获取验证码'
                    };
                  } else {
                    that.message.info('该账号未绑定手机或邮箱，无法注销！');
                  }
                },
                nzCancelText: '取消'
              });
            }
          }
        },
        {
          name: '邮箱', field: 'email', type: COMMON_DETAIL.block,
          operate: {
            name: '修改邮箱',
            style: {marginLeft: '5px'},
            bAuthority: BUTTON_CODE.b_update_email,
            confirmFun(formInfo) {
              if (that.captchaInterval) {
                clearInterval(that.captchaInterval);
              }
              that.isCaptcha = true;
              that.editBasicUser = {
                name: '邮箱验证码',
                isVisible: true
              };
              that.captchaInfo = {
                account: '',
                captcha: '',
                type: 'email',
                buttonName: '获取验证码'
              };
            }
          }
        },
        {
          name: '手机号', field: 'phone', type: COMMON_DETAIL.block,
          operate: {
            name: '修改手机号',
            style: {marginLeft: '5px'},
            bAuthority: BUTTON_CODE.b_update_phone,
            confirmFun(formInfo) {
              if (that.captchaInterval) {
                clearInterval(that.captchaInterval);
              }
              that.isCaptcha = true;
              that.editBasicUser = {
                isVisible: true,
                name: '手机验证码'
              };
              that.captchaInfo = {
                account: '',
                captcha: '',
                type: 'phone',
                buttonName: '获取验证码'
              };
            }
          }
        },
        {name: '初始化管理员', field: 'initialAdmin', type: COMMON_DETAIL.dict, dictType: 'whether'},
        {name: '用户状态', field: 'status', type: COMMON_DETAIL.dict, dictType: 'userStatus'},
        {
          name: '个人信息', type: COMMON_DETAIL.header,
          blockStyle: {marginTop: '10px'},
          operate: {
            name: '修改资料',
            bAuthority: BUTTON_CODE.b_update_user_info,
            style: {fontSize: '14px', marginLeft: '5px'},
            confirmFun(formInfo) {
              that.isVisible = true;
              that.initForm(that.tableDetailModel.formInfo);
            }
          }
        },
        {name: '用户昵称', field: 'nickName', type: COMMON_DETAIL.block},
        {name: '性别', field: 'sex', type: COMMON_DETAIL.dict, dictType: 'sex'},
        {name: '生日', field: 'birthday', type: COMMON_DETAIL.date, dateFormat: 'yyyy-MM-dd'},
        {name: '身份证号', field: 'idCard', type: COMMON_DETAIL.block},
        {
          name: '地址', field: 'address', type: COMMON_DETAIL.block, customShowFun(formInfo) {
            let name = '';
            if (formInfo['countryName']) {
              name += formInfo['countryName'];
              if (formInfo['provinceName']) {
                name += '-' + formInfo['provinceName'];
                if (formInfo['cityName']) {
                  name += '-' + formInfo['cityName'];
                }
              }
            }
            return formInfo['countryName'] ? name : '';
          }
        },
        {name: '头像', field: 'portrait', type: COMMON_DETAIL.lineImg},
        {name: '个人说明', field: 'explain', type: COMMON_DETAIL.line}
      ]
    });
    this.getData();
  }

  ngOnInit() {
  }

  /**
   * 获取数据
   */
  getData() {
    this.homeService.getMyAppUser().subscribe(res => {
      this.userId = res.id;
      this.tableDetailModel.setFormInfo(res);
      this.homeService.getMyAppUserInfo().subscribe(form => {
        Object.assign(this.tableDetailModel.formInfo, form ? form : {});
        const formInfo = this.tableDetailModel.formInfo;
        if (this.tableDetailModel.formInfo['email']) {
          this.tableDetailModel.setModule('email', 'operate.name', '修改邮箱');
        } else {
          this.tableDetailModel.setModule('email', 'operate.name', '设置邮箱');
        }
        if (this.tableDetailModel.formInfo['phone']) {
          this.tableDetailModel.setModule('phone', 'operate.name', '修改手机号');
        } else {
          this.tableDetailModel.setModule('phone', 'operate.name', '设置手机号');
        }
        this.initArea(formInfo);
        if (!this.tableDetailModel.formInfo.portrait) {
          this.tableDetailModel.formInfo.portrait = this.defaultPortrait;
        }
        formInfo.birthday = formInfo.birthday ? CommonTool.turnDate(formInfo.birthday) : null;
      });
    });
  }

  /**
   * 初始化区域
   */
  initArea(form) {
    this.homeService.getMyAppAreaList('root').subscribe(res => {
      for (const arr of res) {
        arr.value = arr.node;
        if (form['country'] === arr.node) {
          this.tableDetailModel.formInfo['countryName'] = arr.name;
        }
      }
      this.countryOptions = res;
    });
    this.homeService.getMyAppAreaList(form['country']).subscribe(res => {
      for (const arr of res) {
        arr.value = arr.node;
        if (form['province'] === arr.node) {
          this.tableDetailModel.formInfo['provinceName'] = arr.name;
        }
      }
      this.provinceOptions = res;
    });
    this.homeService.getMyAppAreaList(form['province']).subscribe(res => {
      for (const arr of res) {
        arr.value = arr.node;
        if (form['city'] === arr.node) {
          this.tableDetailModel.formInfo['cityName'] = arr.name;
        }
      }
      this.cityOptions = res;
    });
  }

  /**
   * 初始化表单
   */
  initForm(form) {
    if (this.defaultPortrait === form.portrait) {
      form.portrait = '';
    }
    const myThis = this;
    this.formInfoModel.initForm({
      components: [
        {
          name: '用户昵称',
          field: 'nickName',
          required: true,
          input: {
            maxLength: 60
          }
        },
        {
          name: '性别',
          field: 'sex',
          required: true,
          select: {
            dictType: 'sex'
          }
        },
        {
          name: '生日',
          field: 'birthday',
          required: true,
          date: {}
        },
        {
          name: '身份证号',
          field: 'idCard',
          required: true,
          input: {
            maxLength: 18
          }
        },
        {
          name: '地址',
          field: 'address',
          required: true,
          linkageSelect: {
            children: [
              {
                name: '省/地区',
                field: 'country',
                options: this.countryOptions,
                initOptionFun($event, formInfo, that) {
                  if ($event) {
                    for (const item of that.selectItem) {
                      if (item.field === 'country') {
                        const array = [];
                        for (const option of item.options) {
                          if (option.status === '0') {
                            array.push(option);
                          }
                        }
                        item.options = array;
                      }
                    }
                  }
                },
                confirmFun(formInfo, that) {
                  formInfo.province = null;
                  formInfo.city = null;
                  if (formInfo.country) {
                    myThis.homeService.getMyAppAreaList(formInfo.country).subscribe(res => {
                      const array = [];
                      for (const arr of res) {
                        if (arr.status === '0') {
                          arr.value = arr.node;
                          array.push(arr);
                        }
                      }
                      for (const item of that.selectItem) {
                        if (item.field === 'province') {
                          item.options = array;
                        }
                        if (item.field === 'city') {
                          item.options = [];
                        }
                      }
                      if (array.length === 1) {
                        formInfo.province = array[0].value;
                        myThis.homeService.getMyAppAreaList(formInfo.province).subscribe(data => {
                          const list = [];
                          for (const arr of data) {
                            if (arr.status === '0') {
                              arr.value = arr.node;
                              list.push(arr);
                            }
                          }
                          for (const item of that.selectItem) {
                            if (item.field === 'city') {
                              item.options = list;
                            }
                          }
                        });
                      }
                    });
                  }
                }
              },
              {
                name: '市',
                field: 'province',
                options: this.provinceOptions,
                confirmFun(formInfo, that) {
                  formInfo.city = null;
                  if (formInfo.province) {
                    myThis.homeService.getMyAppAreaList(formInfo.province).subscribe(res => {
                      const array = [];
                      for (const arr of res) {
                        if (arr.status === '0') {
                          arr.value = arr.node;
                          array.push(arr);
                        }
                      }
                      for (const item of that.selectItem) {
                        if (item.field === 'city') {
                          item.options = array;
                        }
                      }
                    });
                  }
                }
              },
              {
                name: '县/区',
                field: 'city',
                options: this.cityOptions
              }
            ]
          }
        },
        {
          name: '头像',
          field: 'portrait',
          uploadPicture: {
            clickFun(formInfo, component) {
              myThis.uploadLogo(formInfo, component);
            }
          }
        },
        {
          name: '个人说明',
          field: 'explain',
          textarea: {
            rows: 5,
            maxLength: 255
          }
        }
      ]
    }, JSON.parse(JSON.stringify(form)));
  }

  /**
   * 上传logo
   */
  public uploadLogo(formInfo, component) {
    const $this = this;
    $this.formInfoModel.formInfo.portrait = '';
    const input = document.createElement('input');
    input.style.display = 'none';
    input.type = 'file';
    input.setAttribute('multiple', '');
    const event = document.createEvent('MouseEvents');
    event.initEvent('click', true, true); // 这里的click可以换成你想触发的行为
    input.dispatchEvent(event); // 这里的clickME可以换成你想触发行为的DOM结点
    input.onchange = (e) => {
      $this.appService.setLoading(true, '上传中...');
      const file = e.target['files'][0];
      $this.uploadFolderFile(file, {
        folderPath: '/' + $this.userId + '/logo',
        fileName: XcUploadTool.randomFileName(file.name)
      }, component, (downloadUrl) => {
        $this.appService.setLoading(false);
        $this.formInfoModel.formInfo.portrait = downloadUrl;
      });
    };
  }

  /**
   * 上传文件数据处理
   */
  public uploadFolderFile(file, config, component: ArrayConfig, fun) {
    const myThis = this;
    this.personalInfoService.getUploadFileSign().subscribe(res => {
      const xcUploadTool = new XcUploadTool({
        uploadUrl: this.personalInfoService.signUploadFile(), // 上传的url地址
        isHttp: true, // 是否发送http请求
        sign: res,
        loadingStart: (current, data, that) => {
          if (component) {
            component.uploadPicture.loading = true;
          }
        },
        loadingProgress: null,
        loadingSuccess: null,
        uploadStart: null,
        uploadProgress: null,
        uploadSuccess: (current, data, httpRes, that) => {
          if (component) {
            component.uploadPicture.loading = false;
          }
          fun(httpRes.downloadUrl);
        },
        uploadFail: (data, httpRes, that) => {
          if (component) {
            component.uploadPicture.loading = false;
          }
          myThis.appService.setLoading(false);
          myThis.message.error('文件上传失败！');
        }
      }, {file, fileName: config.fileName, folderPath: config.folderPath, resumed: true});
      xcUploadTool.upload();
    });
  }

  /**
   * 提交
   */
  submit(formInfo) {
    const req = {
      nickName: formInfo['nickName'],
      portrait: formInfo['portrait'],
      explain: formInfo['explain'],
      sex: formInfo['sex'],
      birthday: CommonTool.turnDate(formInfo['birthday']),
      idCard: formInfo['idCard'],
      country: formInfo['country'] ? formInfo['country'] : '',
      province: formInfo['province'] ? formInfo['province'] : '',
      city: formInfo['city'] ? formInfo['city'] : ''
    };
    this.appService.setLoading(true);
    this.homeService.updateMyAppUserInfo(req).subscribe(res => {
      this.isVisible = false;
      this.getData();
      this.appService.setLoading(false);
      this.message.success('编辑成功！');
    });
  }

  /**
   * 获取验证码
   */
  public sendCaptcha($event, account, captchaType) {
    if (!account && captchaType !== 'unsubscribe') {
      this.message.warning((this.captchaInfo.type === 'email' ? '新邮箱' : '新手机号') + '不能为空！');
      return;
    }
    if (this.isCaptcha) {
      this.isCaptcha = false;
      this.appService.setLoading(true);
      this.homeService.myAppSendCaptcha({
        accountType: this.captchaInfo.type,
        captchaType,
        account
      }).subscribe(res => {
        this.appService.setLoading(false);
        let index = 60;
        this.captchaInterval = setInterval(() => {
          index--;
          if (index <= 0) {
            this.isCaptcha = true;
            this.captchaInfo.buttonName = '获取验证码';
            clearInterval(this.captchaInterval);
          } else {
            this.captchaInfo.buttonName = index + '秒后重试';
          }
        }, 1000);
      }, () => {
        this.isCaptcha = true;
      });
    }
  }

  /**
   * 修改手机号/邮箱确认提交
   */
  public confirmOk() {
    if (this.captchaInfo.type === 'phone') {
      this.appService.setLoading(true);
      this.homeService.updateMyAppUserPhone({
        phone: this.captchaInfo.account,
        captcha: this.captchaInfo.captcha
      }).subscribe(res => {
        this.editBasicUser.isVisible = false;
        this.appService.setLoading(false);
        this.tableDetailModel.formInfo.phone = res.phone;
        this.message.success('操作成功！');
      });
    } else {
      this.appService.setLoading(true);
      this.homeService.updateMyAppUserMail({
        mail: this.captchaInfo.account,
        captcha: this.captchaInfo.captcha
      }).subscribe(res => {
        this.editBasicUser.isVisible = false;
        this.appService.setLoading(false);
        this.tableDetailModel.formInfo.email = res.email;
        this.message.success('操作成功！');
      });
    }
  }

  /**
   * 确认注销
   */
  public logOffConfirmOk() {
    this.homeService.deleteMyAppUser(this.captchaInfo.captcha).subscribe(res => {
      this.logOffBasic.isVisible = false;
      this.appService.setLoading(false);
      this.message.success('操作成功！');
      this.basicService.logOut();
    });
  }
}
